

const db = require("../db/index")
const moment = require("moment")

let get_area_date = (req, res) => {
    let sql1 = "select rp1_area,rp1_date from sp_report_1"
    let rp1_area = []
    let re1_date = []
    return new Promise((resolve, reject) => {
        db.query(sql1, (err, result) => {
            if (err) return res.sendErr(err)
            result.forEach((item, index) => {
                rp1_area.push(item.rp1_area)
                re1_date.push(moment(item.rp1_date).format("YYYY-MM-DD").toString())

                if (index === result.length - 1) {
                    resolve([[...new Set(rp1_area)], [...new Set(re1_date)]])
                }
            });
        })
    })
}
let get_area_number = (areaArr, res) => {
    let obj = {}
    return new Promise((resolve, reject) => {
        areaArr.forEach((item, index) => {
            obj[item] = []
            let sql = "select rp1_user_count from sp_report_1 where rp1_area = ?"
            db.query(sql, item, (err, result) => {
                if (err) return res.sendErr(err)

                result.forEach(item2 => {
                    obj[item].push(item2.rp1_user_count)
                })

                if (index === areaArr.length - 1) {
                    resolve(obj)
                }
            })
        })
    })
}
const getReportData = async (req, res) => {
    let [areaArr, dateArr] = await get_area_date(req, res)
    let area_number = await get_area_number(areaArr)
    let series = []
    Object.keys(area_number).forEach((key) => {
        series.push({
            name: key,
            type: "line",
            stack: "Total",
            areaStyle: {},
            emphasis: {
                focus: "series",
            },
            data: area_number[key],
        })
    })

    res.send({
        status: 200,
        message: "统计数据获取成功!",
        data: {
            legend: areaArr,
            xlabel: dateArr,
            series: series
        }
    })

}

module.exports = {
    getReportData
}